package com.cynteka.cyfoman.core.collection;

import com.cynteka.cyfoman.core.ComplexPropertyResolver;
import com.cynteka.cyfoman.core.IPropertyResolver;
import com.cynteka.cyfoman.core.Task;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * User: Sergey
 * Date: 06.08.11
 * Time: 15:03
 */
public class CollectionToDBTask implements Task {
    private String sql;
    private CollectionRegistry collectionRegistry;
    private String collectionId;
    private List<String> columns;
    private DataSource dataSource;
    private IPropertyResolver propertyResolver = new ComplexPropertyResolver();

    public Map<String, Object> getCollectionParams() {
        return collectionParams;
    }

    public void setCollectionParams(Map<String, Object> collectionParams) {
        this.collectionParams = collectionParams;
    }

    private Map<String, Object> collectionParams;

    public CollectionRegistry getCollectionRegistry() {
        return collectionRegistry;
    }

    public void setCollectionRegistry(CollectionRegistry collectionRegistry) {
        this.collectionRegistry = collectionRegistry;
    }

    public String getCollectionId() {
        return collectionId;
    }

    public void setCollectionId(String collectionId) {
        this.collectionId = collectionId;
    }

    public List<String> getColumns() {
        return columns;
    }

    public void setColumns(List<String> columns) {
        this.columns = columns;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public boolean isActive() {
        return true;
    }

    @Override
    public void run() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        ICollection collection = collectionRegistry.getCollection(collectionId);
        Collection items = collection.getItems(collectionParams);
        for(Object item : items) {
            int idx = 0;
            Object[] sqlParams = new Object[columns.size()];
            for(String column : columns) {
                Object value = propertyResolver.getProperty(item, column);
                sqlParams[idx] = value;
                idx++;
            }
            jdbcTemplate.update(sql, sqlParams);
        }
    }
}
